﻿using System;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text;
using Model.Platform.PhysicalData;

namespace BML.Infrastructure.Communicate
{
    /// <summary>
    ///     邮件
    /// </summary>
    public class Email
    {
        
        private static Boolean _isLog = false;

        /// <summary>
        ///    异步发送：取消
        /// </summary>
        public static Int32 SendCancel = 0;
        /// <summary>
        ///     异步发送：错误
        /// </summary>
        public static Int32 SendError = 0;
        /// <summary>
        ///     异步发送：成功
        /// </summary>
        public static Int32 SendSuccess = 0;


        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            //唯一的验证
            var token = (EmailLog)e.UserState;
            

            if (e.Cancelled)
            {
                token.Result = SendCancel;
            }
            token.Result = e.Error != null ? SendError : SendSuccess;
           
            if (_isLog)
            {
                //Log(token);
            }
        }

        /// <summary>
        ///    发送邮件
        /// </summary>
        /// <param name="email">邮件地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <param name="displayName">发件人名称</param>
        /// <param name="isBodyHtml">是否为HTML格式</param>
        /// <param name="smtpUser">smtp用户名</param>
        /// <param name="smtpPwd">stmp用户密码</param>
        /// <param name="smtpUrl">stmp服务器</param>
        /// <param name="isLog">是否为邮件记录日志</param>
        /// <param name="isAsync">是否异步</param>
        public static void SendMail(string email, string title, string content, String displayName, Boolean isBodyHtml,
                                             string smtpUser, string smtpPwd, string smtpUrl, Boolean isLog, Boolean isAsync)
        {
            _isLog = isLog;

            var msg = new MailMessage
                {
                    From = new MailAddress(smtpUser, displayName),
                    Subject = title,
                    SubjectEncoding = Encoding.UTF8,
                    Body = content,
                    BodyEncoding = Encoding.UTF8,
                    IsBodyHtml = isBodyHtml,
                    Priority = MailPriority.High
                };
            /*   
            * msg.To.Add("b@b.com");   
            * msg.To.Add("b@b.com");   
            * msg.To.Add("b@b.com");可以发送给多人
            * msg.CC.Add("c@c.com");   
            * msg.CC.Add("c@c.com");可以抄送给多人 
            */
            msg.To.Add(email);


            var client = new SmtpClient
                {
                    Credentials = new NetworkCredential(smtpUser, smtpPwd),
                    Host = smtpUrl
                };
            var logmsg = new EmailLog
                {
                    Id = Guid.Empty,
                    ToAddress = email,
                    Body = msg.Body,
                    DisplayName = msg.From.DisplayName,
                    From = msg.From.Address,
                    IsBodyHtml = msg.IsBodyHtml.ToString(),
                    Subject = msg.Subject,
                    SmtpHost = smtpUrl,
                    SmtpPwd = smtpPwd,
                    SmtpUser = smtpUser
                };

            if (isAsync)
            {
                // Set the method that is called back when the send operation ends.
                client.SendCompleted += new
                    SendCompletedEventHandler(SendCompletedCallback);
                client.SendAsync(msg, logmsg);//简单一点儿可以client.Send(msg);
                //client.SendAsyncCancel(); 
            }
            else
            {
                //TODO:记录系统 Log
                client.Send(msg);
                // Clean up.
                msg.Dispose();
            }





        }



        private static void Log(EmailLog log)
        {
            using (Model.Manager.DataBase.IDbContext db = Model.Manager.ContextFactory.GetPlatformConnect())
            {
                db.GetOperator<EmailLog>().Create(log);
                db.SaveAllChange();
            }
        }


    }
}